﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GameStateManagement
{
    public class Sphere : Microsoft.Xna.Framework.DrawableGameComponent
    {
        public Matrix worldTransformMatrix;
        protected float fScale;
        protected Vector3 vWorldPosition;
        protected Quaternion qRotation;
        protected bool hasChanged;

        protected Texture2D m_ColorMap, m_CelMap;

        protected Model actorModel;
        protected ContentManager contentManager;
        protected Matrix[] actorBones;
        protected Utils.Timer timers;

        public BoundingSphere ModelBounds;
        public BoundingSphere WorldBounds;
        Vector4 vLightDirection;
        protected Effect celEffect, outlineEffect;

        public Target target;

        protected bool followCam;
        protected bool first; 

        protected Game game;
        public Sphere(Game game)
            : base(game)
        {
            this.game = game;
            timers = new Utils.Timer();
            worldTransformMatrix = Matrix.Identity;
            vWorldPosition = new Vector3(0.0f, 0.0f, 0.0f);
            qRotation = Quaternion.Identity;
            fScale = 2.5f;

            first = true;
            hasChanged = true;
            followCam = true;

            target = new Target(game);
            game.Components.Add(target);
            target.Initialize();
            target.followCam = this.followCam;
            vLightDirection = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);


            
        }

        public override void Initialize()
        {
            base.Initialize();
            

        }

        public float Scale
        {
            get { return fScale; }
            set
            {
                fScale = value;
                hasChanged = true;
            }
        }

        public Vector3 Position
        {
            get { return vWorldPosition; }
            set
            {
                vWorldPosition = value;
                hasChanged = true;
            }
        }

        public Quaternion Rotation
        {
            get { return qRotation; }
            set { qRotation = value; }
        }

        public void switchCam()
        {
            followCam = !followCam;
            target.followCam = this.followCam;
        }

        public void updateWorldTransformMatrix()
        {
            Matrix scaleMatrix = Matrix.CreateScale(fScale);
            Matrix rotationMatrix = Matrix.CreateFromQuaternion(qRotation);
            Matrix translationMatrix = Matrix.CreateTranslation(vWorldPosition);

            worldTransformMatrix = scaleMatrix;
            worldTransformMatrix *= rotationMatrix;
            worldTransformMatrix *= translationMatrix;

            WorldBounds.Center = vWorldPosition;
            WorldBounds.Radius = ModelBounds.Radius * fScale;

            
        }

        public override void Update(GameTime gameTime)
        {
            if (hasChanged)
            {
                updateWorldTransformMatrix();
                hasChanged = false;
            }


            if (first)
            {
                Random random = new Random();
                float fzAngle, fyAngle;
                fzAngle = (float)(random.NextDouble() * Math.PI);
                fyAngle = (float)(random.NextDouble() * Math.PI);

                float x = getRadius() * (float)(Math.Sin(fyAngle) * Math.Sin(fzAngle));
                float y = getRadius() * (float)Math.Cos(fyAngle);
                float z = getRadius() * (float)(Math.Sin(fyAngle) * Math.Cos(fzAngle));

                Vector3 pos = new Vector3(x, y, z);
                target.Position = pos;
                target.updateRotation();
                first = false;
            }

            timers.Update(gameTime);
            base.Update(gameTime);
        }

        public float getRadius()
        {
            return this.WorldBounds.Radius * 13.5f;
        }

        public void hitSphere()
        {
            fScale -= 0.01f;
            updateWorldTransformMatrix();

            Vector3 oldTargetPos = target.Position;
            oldTargetPos.Normalize();
            oldTargetPos *= getRadius();
            target.Position = oldTargetPos;
            target.updateWorldTransformMatrix();

        }

        public void hitTarget()
        {
            fScale += 0.01f;
            updateWorldTransformMatrix();

            Vector3 oldTargetPos = target.Position;
            oldTargetPos.Normalize();
            oldTargetPos *= getRadius();
            target.Position = oldTargetPos;
            target.updateWorldTransformMatrix();

        }

        protected override void LoadContent()
        {
            contentManager = new ContentManager(Game.Services, "Content");
            actorModel = contentManager.Load<Model>("bubble");
            actorBones = new Matrix[actorModel.Bones.Count];
            celEffect = contentManager.Load<Effect>("Shader");
            outlineEffect = contentManager.Load<Effect>("OutLineShader");
            m_CelMap = contentManager.Load<Texture2D>("Toon");
            m_ColorMap = contentManager.Load<Texture2D>("bubblegum");
            //spriteBatch = new SpriteBatch(GraphicsDevice);
            
            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                ModelBounds = BoundingSphere.CreateMerged(ModelBounds,
                mesh.BoundingSphere);
            }
            //PresentationParameters pp = game.GraphicsDevice.PresentationParameters;
            //renderTarget = new RenderTarget2D(game.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, game.GraphicsDevice.DisplayMode.Format);
            base.LoadContent();

        }

        protected void changeEffectUsedByModel(Model m, Effect e){
            foreach (ModelMesh mesh in m.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = e;
                }
            }
        }

        protected override void UnloadContent()
        {
            contentManager.Unload();
            base.UnloadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            
            GraphicsDevice.RenderState.DepthBufferEnable = true;
            actorModel.CopyAbsoluteBoneTransformsTo(actorBones);
            celEffect.CurrentTechnique = celEffect.Techniques["ToonShader"];
            changeEffectUsedByModel(actorModel, celEffect);
          
            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                foreach (Effect effect in mesh.Effects)
                {
                    
                    Matrix world =  actorBones[mesh.ParentBone.Index] * worldTransformMatrix;
                    Matrix inverse = Matrix.Invert(world);
                    
                    if (followCam)
                    {
                        effect.Parameters["matWorldViewProj"].SetValue(world * GameplayScreen.camera.View * GameplayScreen.camera.Projection);
                       // effect.Projection = GameplayScreen.camera.Projection;
                    }
                    else
                    {
                        effect.Parameters["matWorldViewProj"].SetValue(world * GameplayScreen.CameraMatrix * GameplayScreen.ProjectionMatrix);
                    }
                    /*
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;
                    effect.AmbientLightColor = GameplayScreen.ambientLightColor;
                    effect.DirectionalLight0.DiffuseColor = GameplayScreen.diffuseColor;
                    effect.DirectionalLight0.Direction = GameplayScreen.diffuseDirection;
                    effect.SpecularColor = GameplayScreen.specularColor;
                    effect.SpecularPower = GameplayScreen.specularPower;*/

                    effect.Parameters["matInverseWorld"].SetValue(inverse);
                    effect.Parameters["vLightDirection"].SetValue(vLightDirection);
                    effect.Parameters["ColorMap"].SetValue(m_ColorMap);
                    effect.Parameters["CelMap"].SetValue(m_CelMap);

                }
                mesh.Draw();

            }
            

            base.Draw(gameTime);
        }


    }
}
